package com.yan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yan.crowd.constant.CrowdConstant;
import com.yan.crowd.entity.Admin;
import com.yan.crowd.entity.AdminExample;
import com.yan.crowd.exception.LoginAcctAlreadyInUseException;
import com.yan.crowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.yan.crowd.exception.LoginFailedException;
import com.yan.crowd.util.CrownUtil;
import com.yan.mapper.AdminMapper;
import com.yan.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class adminServiceImpl implements AdminService {

    @Autowired(required = true)
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {

        // 密码加密
        String userPswd = admin.getUserPswd();
        // String password = CrownUtil.md5(userPswd);
        String password = passwordEncoder.encode(userPswd);
        admin.setUserPswd(password);

        // 生成创建时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(date);
        admin.setCreateTime(createTime);

        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_ALREAD_IN_USE);
            }
        }
    }

    @Override
    public Admin getAdminByLoginAccount(String loginAcct, String password) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        if (admins == null || admins.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        if (admins.size() > 1) {
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_NOT_UNIQUE);
        }

        Admin admin = admins.get(0);

        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        String passwordFromDb = admin.getUserPswd();
        String passwordFromAction = CrownUtil.md5(password);
        if (!Objects.equals(passwordFromDb, passwordFromAction)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        List<Admin> admins = adminMapper.selectAdminByKeyword(keyword);

        return new PageInfo<>(admins);
    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void update(Admin admin) {
        // KeySelective表示有选择的更新,对于null的字段不进行更新
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_ALREAD_IN_USE);
            }
        }
    }

    @Override
    public void saveRelationShip(Integer adminId, List<Integer> roleList) {
        // 先删除旧的admin数据,在覆盖新的数据
        adminMapper.deleteRelationShip(adminId);

        if (roleList != null && roleList.size() > 0){
            adminMapper.insertNewRelationShip(adminId,roleList);
        }

    }

    @Override
    public Admin getAdminByLoginAcct(String username) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(username);
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        return admins.get(0);
    }

}
